package com.huhao.smark;

import static com.huhao.smark.Config.*;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.*;
import org.json.JSONObject;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class AccountSecurityActivity extends AppCompatActivity {

    private SharedPreferences sharedPreferences;
    private String token;
    private int userId;
    private EditText etUsername, etOldPassword, etNewPassword;
    private ImageView ivAvatar;
    private TextView tvResult;
    private Button btnChooseAvatar, btnUpdate, btnChangePassword;
    private Bitmap selectedBitmap;
    private ActivityResultLauncher<Intent> pickImageLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_security);

        // 初始化SharedPreferences
        sharedPreferences = getSharedPreferences("app_prefs", MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getInt("id", -1);

        // 初始化UI组件
        etUsername = findViewById(R.id.et_username);
        etOldPassword = findViewById(R.id.et_old_password);
        etNewPassword = findViewById(R.id.et_new_password);
        ivAvatar = findViewById(R.id.iv_avatar);
        tvResult = findViewById(R.id.tv_result);
        btnChooseAvatar = findViewById(R.id.btn_choose_avatar);
        btnUpdate = findViewById(R.id.btn_update);
        btnChangePassword = findViewById(R.id.btn_change_password);

        // 创建图片选择启动器
        pickImageLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                            try {
                                Uri imageUri = result.getData().getData();
                                InputStream inputStream = getContentResolver().openInputStream(imageUri);
                                selectedBitmap = BitmapFactory.decodeStream(inputStream);
                                ivAvatar.setImageBitmap(selectedBitmap);
                            } catch (Exception e) {
                                e.printStackTrace();
                                tvResult.setText("选择图片失败: " + e.getMessage());
                            }
                        }
                    }
                });

        // 设置图片选择按钮点击事件
        btnChooseAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                pickImageLauncher.launch(intent);
            }
        });

        // 设置更新按钮点击事件
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUserInfo();
            }
        });

        // 设置修改密码按钮点击事件
        btnChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePassword();
            }
        });
    }

    private void updateUserInfo() {
        // 获取用户输入
        String username = etUsername.getText().toString().trim();

        // 创建请求体
        JSONObject jsonBody = new JSONObject();
        boolean hasDataToUpdate = false;

        try {
            if (!username.isEmpty()) {
                jsonBody.put("username", username);
                hasDataToUpdate = true;
            }

            if (selectedBitmap != null) {
                String base64Image = bitmapToBase64(selectedBitmap);
                jsonBody.put("avatar", "data:image/png;base64," + base64Image);
                hasDataToUpdate = true;
            }

            if (!hasDataToUpdate) {
                Toast.makeText(this, "至少修改一项信息", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            tvResult.setText("准备数据失败: " + e.getMessage());
            return;
        }

        // 创建OkHttpClient
        OkHttpClient client = new OkHttpClient();

        // 创建请求
        String url = HTTP + IP + PORT + USER + "/" + userId;
        RequestBody body = RequestBody.create(jsonBody.toString(), MediaType.get("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(url)
                .put(body)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> {
                    tvResult.setText("更新失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseData = response.body().string();
                        JSONObject jsonResponse = new JSONObject(responseData);
                        if (jsonResponse.optInt("code") == 200) {
                            runOnUiThread(() -> {
                                tvResult.setText("更新成功: " + jsonResponse.optString("message"));
                                // 清空输入
                                etUsername.setText("");
                                ivAvatar.setImageResource(R.drawable.avatar);
                                selectedBitmap = null;
                            });
                        } else {
                            runOnUiThread(() -> {
                                tvResult.setText("更新失败: " + jsonResponse.optString("message"));
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            tvResult.setText("解析响应失败");
                        });
                    }
                } else {
                    runOnUiThread(() -> {
                        tvResult.setText("HTTP错误: " + response.code());
                    });
                }
            }
        });
    }

    private void changePassword() {
        // 获取用户输入
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();

        // 验证输入
        if (oldPassword.isEmpty() || newPassword.isEmpty()) {
            Toast.makeText(this, "请输入旧密码和新密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建请求体
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("oldPassword", oldPassword);
            jsonBody.put("newPassword", newPassword);
        } catch (Exception e) {
            e.printStackTrace();
            tvResult.setText("准备数据失败: " + e.getMessage());
            return;
        }

        // 创建OkHttpClient
        OkHttpClient client = new OkHttpClient();

        // 创建请求
        String url = HTTP + IP + PORT + USER + "/" + userId + "/change-password";
        RequestBody body = RequestBody.create(jsonBody.toString(), MediaType.get("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> {
                    tvResult.setText("修改密码失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseData = response.body().string();
                        JSONObject jsonResponse = new JSONObject(responseData);
                        if (jsonResponse.optInt("code") == 200) {
                            runOnUiThread(() -> {
                                tvResult.setText("修改密码成功: " + jsonResponse.optString("message"));
                                // 清空密码输入框
                                etOldPassword.setText("");
                                etNewPassword.setText("");

                                // 修改密码后退出登录
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putBoolean("isLoggedIn", false);
                                editor.remove("token");
                                editor.remove("account");
                                editor.remove("username");
                                editor.remove("bookCount");
                                editor.remove("id");
                                editor.remove("avatar");
                                editor.apply();

                                // 提示用户重新登录
                                Toast.makeText(AccountSecurityActivity.this, "请使用新密码重新登录", Toast.LENGTH_SHORT).show();

                                // 跳转到登录界面
                                Intent intent = new Intent(AccountSecurityActivity.this, LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                finish();
                            });
                        } else {
                            runOnUiThread(() -> {
                                tvResult.setText("修改密码失败: " + jsonResponse.optString("message"));
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            tvResult.setText("解析响应失败");
                        });
                    }
                } else {
                    runOnUiThread(() -> {
                        tvResult.setText("HTTP错误: " + response.code());
                    });
                }
            }
        });
    }

    // 将Bitmap转换为Base64字符串
    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] imageBytes = stream.toByteArray();
        return Base64.encodeToString(imageBytes, Base64.NO_WRAP);
    }
}